package fs.message {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Dictionary;
	import fs.message.Message;
	/**
	 * ...
	 * @author fs
	 */
	public final class MessageTransmitter{
		private static var _messageList:Object={};
		private static var _filteringHandler:Function;
		private static var _tsmtingMsgModel:Message;
		
		private static var _timerSprite:Sprite=new Sprite();
		private static var _timerCount:int = 0;
		
		public static function registerMessage(messageType:String,handler:Function):void{
			if (null == _messageList[messageType]) {
				_messageList[messageType]=[];
			}
			if((_messageList[messageType] as Array).indexOf(handler)<0){
				(_messageList[messageType] as Array).push(handler);
				
				if (messageType == Message.ON_FRAME&&_timerCount==0) {
					_timerSprite.addEventListener(Event.ENTER_FRAME, onTimer);
				}
			}
		}
		
		static private function onTimer(e:Event):void {
			transmitMessage(Message.ON_FRAME);
		}
		
		public static function unregisterMessage(messageType:String,handler:Function):void {
			if (null != _messageList[messageType]) {
				_filteringHandler = handler;
				_messageList[messageType] = (_messageList[messageType] as Array).filter(filterList);
				_filteringHandler = null;
				
				if (messageType == Message.ON_FRAME) {
					_timerCount--;
					if(_timerCount==0){
						_timerSprite.removeEventListener(Event.ENTER_FRAME, onTimer);
					}
				}
			}
		}		
		
		private static function filterList(handler:Function,index:int,array:Array):Boolean{
			return handler != _filteringHandler;
		}
		
		public static function transmitMessage(messageType:String,content:Object=null):void {
			if (null != _messageList[messageType]) {
				_tsmtingMsgModel = new Message(messageType);
				_tsmtingMsgModel.content = content;
				
				(_messageList[messageType] as Array).forEach(transmitMsgList);
			}
		}
		
		private static function transmitMsgList(handler:Function, index:int, array:Array):void {
			handler.call(null, _tsmtingMsgModel);
		}
	}

}